package zzz.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import zzz.model.Post;
import zzz.model.Reply;
import zzz.service.PostService;
import zzz.service.ReplyService;

@Controller
@RequestMapping("/post")
public class PostAction extends BaseAction{

	@Autowired(required=true)
	PostService postService;
	@Autowired
	ReplyService replyService;
	
	@RequestMapping("/replypost")
	public String replyPost(Reply reply,Map<String,Object> m){
		reply.setUserId(this.getLoginUserId());
		System.out.println(reply.toString());
		int result=replyService.replyPost(reply);
		String herf="postdetail?postId="+reply.getPostId();
		if(result!=0){
			m.put("msg","回复成功");
		    m.put("herf",herf);
		    
		}else{
			m.put("msg","回复失败");
		    m.put("herf",herf);
		}
		return "common/msgModal";
	}
	@RequestMapping("/postlist")
	public String postList(Map<String,List<Post>> m){
		
		List<Post> allPost=postService.findAllPost();
		//System.out.println(allPost.get(0).toString());
		m.put("postLists", allPost);
		return "post/postList";
	}
	
	//查看帖子详情
	@RequestMapping("/postdetail")
	public String postDetail(@RequestParam String postId,Map<String,Object> m){
		Post post=postService.findPostById(postId);
		List<Reply> replys=replyService.findReplyByPost(postId);
		List<Post> newPosts=postService.findNewPost();
		System.out.println(newPosts.toString());
		m.put("postDetail", post);
		m.put("replys", replys);
		m.put("newPosts", newPosts);
		return "post/postDetail";
	}
	
	//进入发布帖子页面
	@RequestMapping("/newpostpage")
	public String newPostPage(){
		return "post/newPost";
	}
	
	//发布帖子
	@RequestMapping("/newpostt")
	public String newPost(Post post){
		Date date=new Date();
		post.setPostTime(date);
		post.setUserId(this.getLoginUserId());
		post.setUserId(this.getLoginUserId());
		postService.newPost(post);
		return "redirect:postlist";
	}
	
	//查看用户发布的帖子
	@RequestMapping("/userposts")
	public String postsByUser(Map<String,List<Post>> m){
		List<Post> userPosts=postService.findPostByUserId(Integer.toString(this.getLoginUserId()));
		m.put("userPosts", userPosts);
		return "post/userPostsList";
	}
}
